package com.iyao_app.im.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.iyao_app.Friends.LQRAdapterForRecyclerView;
import com.iyao_app.Friends.LQRViewHolderForRecyclerView;
import com.iyao_app.R;
import com.iyao_app.im.imageloader.ImageLoaderManager;
import com.iyao_app.im.nimsdk.utils.LogUtils;
import com.iyao_app.im.nimsdk.utils.NimMessageSDK;
import com.iyao_app.im.uitl.Bimp;
import com.iyao_app.util.ResourcesUtils;
import com.iyaowoqu.base_library.util.ImageUtils;
import com.iyaowoqu.base_library.util.LogUtil;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.attachment.ImageAttachment;
import com.netease.nimlib.sdk.msg.constant.MsgDirectionEnum;
import com.netease.nimlib.sdk.msg.constant.MsgTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by xue on 2017/11/21.
 */

public class ChatAdapter extends LQRAdapterForRecyclerView<IMMessage> {

    private Context mContext;
    private List<IMMessage> emMessageList = new ArrayList<>();

    private static final int SEND_TEXT = R.layout.list_item_chat_send;
    private static final int RECEIVE_TEXT = R.layout.list_item_chat_receive;
    private static final int SEND_IMAGE = R.layout.item_image_send;
    private static final int RECEIVE_IMAGE = R.layout.item_image_receive;

    public ChatAdapter(Context context, List<IMMessage> data) {
        super(context, data);
        this.mContext = context;
        this.emMessageList = data;
    }

    public ChatAdapter(Context context, int defaultLayoutId, List<IMMessage> data) {
        super(context, defaultLayoutId, data);
    }

    @Override
    public void convert(LQRViewHolderForRecyclerView helper, IMMessage item, int position) {
        if (item.getMsgType() == MsgTypeEnum.text) {
            setTextMessage(helper, emMessageList.get(position));
        } else if (item.getMsgType() == MsgTypeEnum.image) {
            setImageMessage(helper, item);
        }
        SimpleDraweeView headView = helper.getView(R.id.iv_avatar);
        try {
            Map<String, Object> remoteExtension = item.getRemoteExtension();
            LogUtil.e("==remoteExtension          Chat===>" + remoteExtension);
            if (remoteExtension != null) {
                String fromNickName = (String) remoteExtension.get("fromNickName");
                String toAvatar = (String) remoteExtension.get("toAvatar");
                String toNickName = (String) remoteExtension.get("toNickName");
                String fromAvatar = (String) remoteExtension.get("fromAvatar");
                String head = null;
                LogUtil.e("===SEND_TEXT====>" + position + "===" + fromAvatar);

                Uri uri = Uri.parse(fromAvatar);
                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                        .setResizeOptions(new ResizeOptions((int) ResourcesUtils.getDimension(R.dimen.x80), (int) ResourcesUtils.getDimension(R.dimen.x80)))
                        .build();
                PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                        .setOldController(headView.getController())
                        .setImageRequest(request)
                        .build();
                headView.setController(controller);

            } else {
                headView.setImageResource(R.drawable.ic_guanlogo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setTextMessage(LQRViewHolderForRecyclerView helper, IMMessage item) {
        helper.setText(R.id.tv_msg, item.getContent());
    }

    private void setImageMessage(LQRViewHolderForRecyclerView helper, final IMMessage item) {
        //把图片赋值到布局上
        final ImageView bivPic = helper.getView(R.id.tv_msgs);
        final ImageAttachment ia = (ImageAttachment) item.getAttachment();
        LogUtil.e("===="+ia.getPath()+"==="+ia.getDisplayName()+"==="+ia.getWidth());
        if (!TextUtils.isEmpty(ia.getPath())) {
            LogUtil.e("========ia.getPath()======");
            try {
//                bivPic.setImageURI(ImageUtils.IMAGE_FILE + ia.getPath());
                Glide.with(mContext).load(ia.getPath()).into(bivPic);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {

            //判断本地是否有缩略图
            if (ia.getThumbPath() == null) {
                LogUtil.e("本地没有缩略图");

                AbortableFuture abortableFuture = NimMessageSDK.downloadAttachment(item, true);
                abortableFuture.setCallback(new RequestCallback() {
                    @Override
                    public void onSuccess(Object param) {
                        Bitmap bitmap = Bimp.getLoacalBitmap(ia.getThumbPath());
                        if (bitmap != null) {
                            bivPic.setImageBitmap(bitmap);
                        }
                    }

                    @Override
                    public void onFailed(int code) {

                    }

                    @Override
                    public void onException(Throwable exception) {

                    }
                });
            } else {
                LogUtil.e("本地有缩略图");
                Bitmap bitmap = Bimp.getLoacalBitmap(ia.getThumbPath());
                if (bitmap != null) {
                    bivPic.setImageBitmap(bitmap);
                }
            }
        }

    }

    @Override
    public int getItemViewType(int position) {

        IMMessage msg = getData().get(position);

        MsgTypeEnum msgType = msg.getMsgType();
        if (msgType == MsgTypeEnum.text) {
            if (msg.getDirect() == MsgDirectionEnum.Out) {
                return SEND_TEXT;
            } else {
                return RECEIVE_TEXT;
            }
        }
        if (msgType == MsgTypeEnum.image) {
            if (msg.getDirect() == MsgDirectionEnum.Out) {
                return SEND_IMAGE;
            } else {
                return RECEIVE_IMAGE;
            }
        }

        return super.getItemViewType(position);
    }

}
